package com.car.rental.gateway.filter;

import com.car.rental.common.constant.Constants;
import com.car.rental.common.utils.JwtUtils;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;

@Component
@Order(0)
public class AuthFilter implements GlobalFilter, Ordered {

    private final JwtUtils jwtUtils;
    
    @Autowired
    public AuthFilter(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }
    
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);
    
    // 白名单路径
    private static final String[] WHITE_LIST = {
        "/auth/login",
        "/auth/register",
        "/auth/validate",
        "/payment/alipay/notify",
        "/order/",
        "/vehicle/uploads/",
        "/user/uploads/"
    };

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        
        // 静态资源请求跳过认证
        if (path.matches(".*/uploads/.*")) {
            return chain.filter(exchange);
        }
        
        log.info("请求进入网关: path={}", path);
        
        // 白名单放行
        for (String whitePath : WHITE_LIST) {
            if (path.startsWith(whitePath)) {
                log.info("白名单路径: {}", path);
                return chain.filter(exchange);
            }
        }
        
        // 其他请求进行认证
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (token == null || !token.startsWith(Constants.TOKEN_PREFIX)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        
        // 验证token
        token = token.substring(Constants.TOKEN_PREFIX.length());
        if (!jwtUtils.validateToken(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
} 